package com.soulapp.hook.hooker

import android.annotation.SuppressLint
import android.widget.Toast
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData
import java.text.SimpleDateFormat

// 信息可随时撤回
object CanRecallHook : BaseHooker() {
    private const val TAG = "CanRecallHook"
    private var hook: Result? = null

    override fun getKey() = ConfigData.canRecall

    override fun onHook() {
        startHook()
    }

    @SuppressLint("SimpleDateFormat")
    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        val className = "cn.soulapp.imlib.msg.ImMessage"
        hook = className.toClass().resolve()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("getLocalTime")
                emptyParameters()
                returnType == Long::class.javaPrimitiveType
            }.first()
            .hook {
                replaceAny {
                    val currentTime = System.currentTimeMillis()
                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    if (showToast) {
                        val formatTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime)
                        Toast.makeText(appContext, "消息撤回--$formatTime", Toast.LENGTH_SHORT).show()
                    }
                    currentTime
                }
            }
    }

    override fun stopHook() {
        YLog.debug("stopHook $TAG $hookEnabled")
        if (hookEnabled) return

        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")
    }

}
